package com.bignerdranch.android.ecar.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.bignerdranch.android.ecar.PhotoPicker.PhotoAdapter;
import com.bignerdranch.android.ecar.PhotoPicker.RecyclerItemClickListener;
import com.bignerdranch.android.ecar.R;
import com.bignerdranch.android.ecar.Utils.RequestUtil;
import com.bignerdranch.android.ecar.Utils.URLBank;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.PhotoPreview;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class BlogEditActivity extends BaseActivity implements View.OnClickListener {

    private ImageButton blog_edit_back;
    private ImageButton send;
    private EditText edit_blog;
    private RecyclerView recycle_img;
    ArrayList<String> selectedPhotos = new ArrayList<>();
    PhotoAdapter photoAdapter;
    String url;
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/*");

    private final OkHttpClient client = new OkHttpClient();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blog_edit);
        initView();
    }

    private void initView() {
        blog_edit_back = (ImageButton) findViewById(R.id.blog_edit_back);
        send = (ImageButton) findViewById(R.id.send);
        edit_blog = (EditText) findViewById(R.id.edit_blog);
        photoAdapter = new PhotoAdapter(this, selectedPhotos);
        recycle_img = (RecyclerView) findViewById(R.id.recycle_img);
        recycle_img.setLayoutManager(new StaggeredGridLayoutManager(4, OrientationHelper.VERTICAL));

        recycle_img.setAdapter(photoAdapter);


        blog_edit_back.setOnClickListener(this);
        send.setOnClickListener(this);


        recycle_img.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
               /* if (position != (selectedPhotos.size()-1)&&selectedPhotos.size()!=0){
                    PhotoPreview.builder()
                            .setPhotos(selectedPhotos)
                            .setCurrentItem(position)
                            .start(BlogEditActivity.this);
                }else {*/
                PhotoPicker.builder()
                        .setPhotoCount(9)
                        .setGridColumnCount(4)
                        .start(BlogEditActivity.this);
            }

//            }
        }));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.blog_edit_back:

                finish();
                break;
            case R.id.send:
                Log.e("====", selectedPhotos.size() + "");
                uploadImg();

                checkResult();
                break;

        }
    }

    private void checkResult() {
        RequestUtil.executeJSONObject(this, url, new com.android.volley.Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject o) {
                try {
                    String answer = o.getString("code");
                    Log.e("=====",answer);
                    if (answer.equals("0")) {
                        Toast.makeText(getApplicationContext(), "上传成功", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK &&
                (requestCode == PhotoPicker.REQUEST_CODE || requestCode == PhotoPreview.REQUEST_CODE)) {

            List<String> photos = null;
            if (data != null) {
                photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
            }
            selectedPhotos.clear();

            if (photos != null) {

                selectedPhotos.addAll(photos);
            }
            photoAdapter.notifyDataSetChanged();
        }
    }

    private void uploadImg() {
        url = URLBank.teacher_url + URLBank.addNote_url;
        Log.e("=====",url);
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (int i = 0; i < selectedPhotos.size(); i++) {
            File f = new File(selectedPhotos.get(i));
            if (f != null) {
                builder.addFormDataPart("img", f.getName(), RequestBody.create(MEDIA_TYPE_PNG, f));
            }
        }
        //添加其它信息
        builder.addFormDataPart("userId", "52").addFormDataPart("content", edit_blog.getText().toString());
        MultipartBody requestBody = builder.build();
        //构建请求
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)//添加请求体
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("_____", "上传失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e("上传照片成功：response = ", response.body().string());
            }
        });


    }

}
